﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CustomProvider
{
    /// <summary>
    /// The class supports extension methods
    /// </summary>
    public static class ExtensionMethodProvider
    {
        /// <summary>
        /// Replaces a character in a string with the character specified.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="index"></param>
        /// <param name="charToUse"></param>
        /// <returns></returns>
        public static string ReplaceCharWithChar(this string s, int index, char charToUse)
        {
            char[] tmpBuffer = s.ToCharArray();
            tmpBuffer[index] = charToUse;
            return new string(tmpBuffer);
        }

        /// <summary>
        /// Build a string that presents the positions of specified character in a string
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string BuildSearchedCharacters(this string s, string character)
        {
            var sPositions = string.Empty;
            // Create the positon array of pattern character
            // -1: character is not existent in the string
            Func<char, int, int> findSelector = (c1, posc1) =>
            {
                // Checking selected character is match with the pattern character
                Predicate<char> compareSelector = (c2) =>
                {
                    return char.ToUpper(c2).Equals(char.ToUpper(char.Parse(character)));
                };
                return compareSelector(c1) ? posc1 : -1;
            };
            var positions = s.Select(findSelector).Where(n => n != -1);

            foreach (int pos in positions)
                sPositions += pos.ToString() + ",";

            sPositions = sPositions.Substring(0, sPositions.Length - 1);
            return sPositions;
        }

        /// <summary>
        /// Determines whether this instance and another specified System.String object have the different value.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool NonEquals(this string s, string value)
        {
            return !s.Equals(value);
        }

        /// <summary>
        /// Determines whether this instance is enable to convert to numeric
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNumeric(this string s)
        {
            double val;
            return double.TryParse(s, out val);
        }
    }
}
